﻿/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml.Serialization;
using MyPhotoIndex.Utilities;
using MyPhotoIndex.Interfaces.Imaging;
using MyPhotoIndex.ImageBank;
using MyPhotoIndex.Interfaces.Tagging;
using blowery.Web.HttpCompress;
using MyPhotoIndex.ImageBank.Query;

namespace MyPhotoIndex.Plugins.WebHost.RequestHandlers
{
    public class ImageListRequestHandler : IRequestHandler
    {
        public void Process(HttpListenerRequest request, HttpListenerResponse response)
        {
            QueryParameters query = null;

            try
            {
                using (Stream input = request.InputStream)
                using (StreamReader sr = new StreamReader(input))
                {
                    string str = sr.ReadToEnd();
                    str = System.Web.HttpUtility.UrlDecode(str);
                    str = str.Remove(0, 2);

                    XmlSerializer inputSerializer = new XmlSerializer(typeof(QueryParameters));
                    query = (QueryParameters)inputSerializer.Deserialize(new StringReader(str));
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }

            List<IImageData> imageList = null;

            if (query == null ||
                ((query.Tags == null ||
                query.Tags.Length == 0) &&
                string.IsNullOrEmpty(query.Comment) == true))
            {
                imageList = new List<IImageData>(Storage.Instance.UnFiltered.Values);
            }
            else
            {
                if (string.IsNullOrEmpty(query.Comment) == false)
                {
                    string commentToSearch = query.Comment.Trim().Substring(0, Math.Min(20, query.Comment.Length));
                    CommentQueryParameter qp = new CommentQueryParameter(commentToSearch);
                    QueryBuilder queryBuilder = new QueryBuilder(new QueryParameter[] { qp }, new QueryHelper(Storage.Instance.UnFiltered), true);
                    Dictionary<int, IImageData> result = queryBuilder.RunQuery();

                    imageList = new List<IImageData>();
                    foreach (IImageData imageData in result.Values)
                    {
                        imageList.Add(imageData);
                    }
                }
                else
                {
                    List<int> tagList = new List<int>(query.Tags);

                    List<int> withAnd = new List<int>();
                    List<int> withOr = new List<int>();
                    List<int> without = new List<int>();

                    foreach (int tagId in query.Tags)
                    {
                        IImageTag tag = ImageTagCollection.Instance.GetTag(tagId);
                        if (tag.Parent != null &&
                           (tagList.Contains(tag.Parent.Id) || tag.ChildTags.Count > 0))
                        {
                            withOr.Add(tagId);
                        }
                        else
                        {
                            withAnd.Add(tagId);
                        }
                    }

                    SavedQuery savedQuery = new SavedQuery();
                    savedQuery.WithAnd = withAnd.ToArray();
                    savedQuery.WithOr = withOr.ToArray();
                    savedQuery.Without = without.ToArray();

                    List<int> imageIdsList = savedQuery.ExecuteQuery(true);

                    imageList = new List<IImageData>();
                    foreach (int imageId in imageIdsList)
                    {
                        imageList.Add(Storage.Instance.UnFiltered[imageId]);
                    }
                }
            }

            List<ImageInfo> imageInfoList = new List<ImageInfo>();
            foreach (IImageData imageData in imageList)
            {
                if (imageData.Encrypted == false)
                {
                    ImageInfo imageInfo = new ImageInfo();
                    // string baseUrl = request.IsSecureConnection ? "https://" : "http://" + request.Url.Host + ":" + request.Url.Port;
                    imageInfo.Thumbnail = string.Format("{0}.jpg", imageData.Id);
                    imageInfo.Comment = imageData.Comment;
                    imageInfo.DateTaken = imageData.DateTaken;
                    imageInfo.Rating = imageData.Rating;
                    imageInfo.Tags = imageData.Tags;

                    imageInfoList.Add(imageInfo);
                }
            }

            response.ContentType = Utils.GetContentTypeFromFileExtention(".xml");
            response.AppendHeader("Content-Encoding", "gzip");
            response.AppendHeader("X-Compressed-By", "HttpCompress");
            response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate");

            XmlSerializer serializer = new XmlSerializer(typeof(ImageInfo[]));

            using (Stream output = response.OutputStream)
            {
                using (GZipFilter gzip = new GZipFilter(output))
                {
                    serializer.Serialize(gzip, imageInfoList.ToArray());
                }
            }
        }
    }
}
